<?php

/**
 * 微信扫码支付
 */

namespace app\wechat\controller;

class WebPayController extends \app\member\common\MemberCommon {

    public function index() {
        $token = request('get', 'token');
        $data = request('get');
        ksort($data);
        unset($data['token']);
        $token = base64_decode($token);
        $config = \Config::get('dux.use');
        $valToken = hash_hmac('sha1', http_build_query($data), $config['safe_key'], true);

        if($token <> $valToken) {
            $this->error('token验证失败!');
        }

        if($data['tmp'] + 300 < time()) {
            $this->error('支付已过期，请重新支付！');
        }

        $this->pageInfo['name'] = '扫码支付';
        $this->setMeta('扫码支付');
        $this->setCrumb([
            [
                'name' => '扫码支付',
                'url' => url()
            ]
        ]);

        //扫码支付
        $notifyUrl = url('api/wechat/WechatMobile/index');
        $config = $this->payConfig($notifyUrl);
        $ip = \dux\lib\Client::getUserIp();

        $payData = [
            'order_no' => $data['order_no'],
            'amount' => $data['money'] ? $data['money'] : 0,
            'client_ip' => ($ip == '::1') ?  '127.0.0.1' : $ip,
            'subject' => str_len($data['title'], 125),
            'body' => $data['body'] ? $data['body'] : $data['title'],
            'extra_param' => $data['app'],
            'product_id' => $data['order_no']
        ];

        try {
            $charge = new \Payment\ChargeContext();
            $type = \Payment\Config::WX_CHANNEL_QR;
            $charge->initCharge($type, $config);
            $json = $charge->charge($payData);
            $url = urlencode($json);
            $this->assign('codeUrl', 'http://paysdk.weixin.qq.com/example/qrcode.php?data=' . $url);
            $this->assign('money', $data['money']);
            $this->assign('returnUrl', $data['return_url']);
            $this->assign('orderNo', $data['order_no']);
            $this->memberDisplay('', true, false);
        } catch (\Payment\Common\PayException $e) {
            if($e->errorMessage() == '微信返回错误提示:该订单已支付') {
                $this->redirect($data['return_url']);
            }else {
                $this->error($e->errorMessage());
            }
        }
    }

    public function status() {
        $orderNo = request('', 'order_no', 0);
        if(empty($orderNo)) {
            $this->error('订单号不存在!');
        }
        $query = new \Payment\QueryContext();
        $notifyUrl = url('api/wechat/WechatMobile/index');
        $config = $this->payConfig($notifyUrl);

        try {
            $query->initQuery(\Payment\Config::WEIXIN, $config);
            $data = $query->query(['order_no' => $orderNo]);

            if(empty($data)) {
                $this->error('支付查询失败');
            }

            if($data['is_success'] == 'F') {
                $this->error('查询请求失败');
            }

            if(strtolower($data['response']['trade_state']) == 'success') {
                $this->success('订单支付成功!');
            }
            $this->error('支付失败!');

        } catch (\Payment\Common\PayException $e) {
            $this->error('查询失败');

        }
    }

    private function payConfig($notifyUrl = '') {
        $config = target('member/PayConfig')->getConfig('wechat_mobile');
        if (empty($config['mch_id']) || empty($config['md5_key'])) {
            $this->error('请先配置支付接口信息!');
        }
        $wechatConfig = target('wechat/WechatConfig')->getConfig();
        if(empty($wechatConfig['appid'])) {
            $this->error('公众号ID未设置!');
        }
        $notifyUrl = DOMAIN . $notifyUrl;
        return [
            'app_id' => $wechatConfig['appid'],
            'mch_id' => $config['mch_id'],
            'md5_key' => $config['md5_key'],
            'notify_url' => $notifyUrl,
            'time_expire'	=> 5,
        ];
    }

}